//
//  CQMenuCollectionView.m
//  CJUIKitDemo
//
//  Created by ciyouzen on 2017/9/11.
//  Copyright © 2017年 dvlproad. All rights reserved.
//

#import "CQMenuCollectionView.h"
#import <CJCollectionViewLayout/CQCollectionViewFlowLayout.h>
#import <CJCollectionViewLayout/CJCellHorizontalLayout.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "CQMenuCollectionViewCell.h"
#import "CQMenuCollectionViewDataSource.h"


@interface CQMenuCollectionView () <UICollectionViewDelegateFlowLayout, UICollectionViewDelegate> {
    
}
@property (nonatomic, copy, readonly) void (^didTapShowingItemBlock)(UICollectionView *collectionView, NSIndexPath *indexPath, CQMenuDataModel *dataModel); /**< 点击item的事件 */
@property (nonatomic, strong) CQMenuCollectionViewDataSource *menuCollectionViewDataSource;

@end


@implementation CQMenuCollectionView

/// 初始化方法
- (instancetype)initWithScrollDirection:(UICollectionViewScrollDirection)scrollDirection
                 didTapShowingItemBlock:(void(^)(UICollectionView *collectionView, NSIndexPath *indexPath, CQMenuDataModel *dataModel))didTapShowingItemBlock
{
    UICollectionViewLayout *layout = [self __horizontalLayout];
    if (scrollDirection == UICollectionViewScrollDirectionVertical) {
        layout = [self __verticalLayout];
    }
    self = [super initWithFrame:CGRectZero collectionViewLayout:layout];
    if (self) {
        _didTapShowingItemBlock = didTapShowingItemBlock;
        _maxBadgeNumber = 9;
        
        [self setupConfigure];
        
        self.pagingEnabled = YES;
        self.showsHorizontalScrollIndicator = NO;
    }
    return self;
}

/// 水平滚动的collectionView布局(index顺序能按照横向读完再读下一行)
- (UICollectionViewLayout *)__horizontalLayout {
    CJCellHorizontalLayout *horizontalLayout = [[CJCellHorizontalLayout alloc] init];
    horizontalLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    horizontalLayout.cellWidthFromPerRowMaxShowCount = 4;
    horizontalLayout.widthHeightRatio = 1/1.0;
    
    horizontalLayout.sectionInset = UIEdgeInsetsMake(15, 10, 15, 10);
    horizontalLayout.minimumLineSpacing = 15-4;
    horizontalLayout.minimumInteritemSpacing = 10;
    
    return horizontalLayout;
}

/// 竖直滚动的collectionView布局
- (UICollectionViewLayout *)__verticalLayout {
    CQCollectionViewFlowLayout *verticalLayout = [[CQCollectionViewFlowLayout alloc] init];
    verticalLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    verticalLayout.cellWidthFromPerRowMaxShowCount = 4;
    verticalLayout.widthHeightRatio = 1/1.0;
    
    verticalLayout.sectionInset = UIEdgeInsetsMake(15, 10, 15, 10);
    verticalLayout.minimumLineSpacing = 15-4;
    verticalLayout.minimumInteritemSpacing = 10;
    
    return verticalLayout;
}


- (void)setupConfigure {
    self.backgroundColor = [UIColor clearColor];
    self.layer.cornerRadius = 6;
    
    
    /* 设置Register的Cell或Nib */
    CQMenuCollectionViewCell *registerCell = [[CQMenuCollectionViewCell alloc] init];
    [self registerClass:[registerCell class] forCellWithReuseIdentifier:@"cell"];
    
    __weak typeof(self)weakSelf = self;
    
    /* 创建DataSource */
    CQMenuCollectionViewDataSource *menuCollectionViewDataSource = [[CQMenuCollectionViewDataSource alloc] initWithDataSourceSettingModel:nil cellForItemAtIndexPathBlock:^UICollectionViewCell *(UICollectionView *collectionView, NSIndexPath *indexPath, BOOL isExtralItem) {
        if (!isExtralItem) {
            CQMenuCollectionViewCell *dataCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
            //dataCell.backgroundColor = [UIColor redColor];
            NSLog(@"dataCell.selected = %@", dataCell.selected ? @"YES" : @"NO");
            [weakSelf __operateDataCell:dataCell withIndexPath:indexPath isSettingOperate:YES];

            return dataCell;
        } else {
            CQMenuCollectionViewCell *extralCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addCell" forIndexPath:indexPath];
            extralCell.iconImageView.image = [UIImage imageNamed:@"cjCollectionViewCellAdd"];
            
            return extralCell;
        }
    }];
    self.menuCollectionViewDataSource = menuCollectionViewDataSource;
    
    
    /* 设置DataSource和Delegate */
    //self.dataSource = self;
    self.delegate = self;
    self.dataSource = self.menuCollectionViewDataSource;
}

#pragma mark - Getter
/*
*  获取collectionView的高度
*
*  @param marginLeft         collectionView与屏幕的左边距
*  @param marginRight        collectionView与屏幕的右边距
*  @param maxRowCount        允许的最大行数(不限制时候可设为NSIntegerMax)
*
*  @return
*/
- (CGFloat)heightByScreenMarginLeft:(CGFloat)marginLeft
                  screenMarginRight:(CGFloat)marginRight
                        maxRowCount:(NSInteger)maxRowCount
{
    CGFloat screenWidth = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    CGFloat collectionViewWidth = screenWidth-marginLeft-marginRight;

    NSInteger allCellCount = self.menuCollectionViewDataSource.dataModels.count;
    
    CGFloat height = 0;
    UICollectionViewLayout *layout = (UICollectionViewLayout *)self.collectionViewLayout;
    if ([layout isKindOfClass:[CJCellHorizontalLayout class]]) {
        height = [CJCellHorizontalLayout heightForAllCellCount:allCellCount maxRowCount:maxRowCount byCollectionViewWidth:collectionViewWidth withCollectionViewLayout:layout];
    } else if ([layout isKindOfClass:[CQCollectionViewFlowLayout class]]) {
        height = [CQCollectionViewFlowLayout heightForAllCellCount:allCellCount maxRowCount:maxRowCount byCollectionViewWidth:collectionViewWidth withCollectionViewLayout:layout];
    }
    
    return height;
}

#pragma mark - Setter
- (void)setDataModels:(NSMutableArray<CQMenuDataModel *> *)dataModels {
    _dataModels = dataModels;
    self.menuCollectionViewDataSource.dataModels = dataModels;
}



#pragma mark - UICollectionViewDelegate
//“点到”item时候执行的时间(allowsMultipleSelection为默认的NO的时候，只有选中，而为YES的时候有选中和取消选中两种操作)
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"当前点击的Item为数据源中的第%zd个", indexPath.item);
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    CQMenuDataModel *dataModel = [self.menuCollectionViewDataSource dataModelAtIndexPath:indexPath];
    if (self.didTapShowingItemBlock) {
        self.didTapShowingItemBlock(collectionView, indexPath, dataModel);
    }
}


#pragma mark - Private Method
/*
 *  设置或者更新Cell
 *
 *  @param cell             要设置或者更新的Cell
 *  @param indexPath        要设置或者更新的Cell的indexPath
 *  @param isSettingOperate 是否是设置，如果否则为更新
 */
- (void)__operateDataCell:(CQMenuCollectionViewCell *)dataCell
                withIndexPath:(NSIndexPath *)indexPath
            isSettingOperate:(BOOL)isSettingOperate
{
    CQMenuDataModel *dataModel = [self.menuCollectionViewDataSource dataModelAtIndexPath:indexPath];
    
    if (isSettingOperate) {
        [dataCell.iconImageView sd_setImageWithURL:[NSURL URLWithString:dataModel.imageUrl] placeholderImage:dataModel.imagePlaceholderImage];
        dataCell.titleNameLabel.text = dataModel.name;
        [dataCell setupBadgeCount:dataModel.badgeCount withMaxNumber:self.maxBadgeNumber];
    }
}


@end
